import axios from "axios";
import router from "../router/index";
import { baseUrl } from "./env";

axios.defaults.withCredentials = true;
// axios.defaults.headers.common["Access-Control-Allow-Headers"] =
//   "Origin,X-Requested-with,Content-Type,Accept,app_token";
const service = axios.create({
  baseURL: baseUrl, // api 的 base_url
  timeout: 3000000, // request timeout 单位毫秒 超时为50分钟
  changeOrigin: true, //跨域
  withCredentials: true, // 跨域携带cookie
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    console.log('request config:',config);
    config.headers.APP_TOKEN = localStorage.appToken || "";
    config.headers.sessionId = localStorage.sessionId ||"";
    return config;
  },
  error => {
    // Do something with request error
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    var _this = this;
    // 后端报错处理
    if (response.data.status != "1") {
      if ("01" == response.data.code) {
        alert("登录已经过期，请重新登录");
        setTimeout(function() {
          localStorage.removeItem("islogin");
          localStorage.appToken = "";
          router.push({ path: "/login" });
        }, 1500);
      } else {
        // 依据code码做错误处理
        return response;
      }
    } else {
      // 请求正常
      return response;
    }
  },
  error => {
    let message =
      error.code === "ECONNABORTED"
        ? `<i class="el-icon-warning"></i>网络请求超时`
        : `<i class="el-icon-warning"></i>系统错误，请联系管理员</a>`;
    this.$alert(message, {
      confirmButtonText: "确定",
      callback: action => {
        this.$message({
          type: "info",
          message: `action: ${action}`
        });
      }
    });

    return Promise.reject(error);
  }
);

export default service;
